package com.mhc.suzuki.service.impl;

import com.mhc.haval.api.service.IStaffRoleService;
import com.mhc.haval.security.model.Role;
import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.*;
import com.mhc.suzuki.constant.*;
import com.mhc.suzuki.dal.mapper.ext.CreditQueryApplyExtMapper;
import com.mhc.suzuki.dal.mapper.ext.OrderAuditTaskExtMapper;
import com.mhc.suzuki.dal.model.*;
import com.mhc.suzuki.dal.query.*;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.*;
import com.mhc.suzuki.service.AuditTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Churry
 * @create 2017-09-14 14:12
 **/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class AuditTaskServiceImpl implements AuditTaskService {

    @Autowired
    OrderAuditTaskManager orderAuditTaskManager;
    @Autowired
    OrderAuditApplyManager orderAuditApplyManager;
    @Autowired
    CreditQueryApplyExtMapper creditQueryApplyExtMapper;
    @Autowired
    OrderAuditTaskExtMapper orderAuditTaskExtMapper;
    @Autowired
    private IStaffRoleService staffRoleService;

    /**
     * 获取我的审核待办列表
     *
     * @param staffId
     * @param queryMap
     * @return
     */
    @Override
    public List<AuditTaskBO> getAuditTaskList(Long staffId, Map queryMap) throws SuzukiCommonException {
        Optional<Long> staffIdOptional = Optional.ofNullable(staffId);
        if (!staffIdOptional.isPresent()) {
            throw new SuzukiCommonException(ErrorCodeEnum.STAFF_ID_ISNULL);
        }
        queryMap.put("staffId", staffId);
        List<AuditTaskBO> auditTaskBOList = new ArrayList<>();
        for (AuditTaskBO auditTaskBO : orderAuditTaskExtMapper.getWaitingTaskListByStaffId(queryMap)) {
            auditTaskBO.setApplyTypeDesc(ApplyTypeEnum.getApplyTypeEnum(auditTaskBO.getApplyType()).getName());
            auditTaskBOList.add(auditTaskBO);
        }
        //查询的结果为空属于合理存在的现象，所以没有自定义抛出异常
        return auditTaskBOList;
    }

    /**
     * 获取GPS确认列表
     * @param queryMap
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public List<AuditTaskBO> getGPSTaskList(Map queryMap) throws SuzukiCommonException {
        log.info("开始查询GPS确认列表...");
        /**查询资产保全部的id**/
//        Long approveStaffId = staffRoleService.selectRole(RoleTypeEnum.ROLE_ASSETS.getCode());
//        queryMap.put("approveStaffId",approveStaffId);
        return orderAuditTaskExtMapper.getGPSTaskList(queryMap);
    }

    /**
     * 获取订单审核进度（包含订单所有的申请进度）
     *
     * @param orderNo
     * @return
     */
    @Override
    public List<AuditProgressBO> getAuditStatusList(User logedUser, String orderNo) throws SuzukiCommonException {
        Optional<String> orderNoOptional = Optional.ofNullable(orderNo);
        if (orderNoOptional.isPresent()) {
            try {
                List<AuditProgressBO> auditProgressBOList = new ArrayList<>();
                AuditProgressBO auditProgressBO = new AuditProgressBO();
                //征信录入是第一个节点
                List<CreditQueryApplyBO> creditInfoList = creditQueryApplyExtMapper.selectByCreditInfo(orderNo);
                if (creditInfoList.size() > 0) {
                    CreditQueryApplyBO creditQueryApplyBO = creditInfoList.get(0);
                    auditProgressBO.setNodeId(creditQueryApplyBO.getCreditQueryApplyId());
                    auditProgressBO.setNodeName(ApplyTypeEnum.CREDITED.getName());
                    auditProgressBO.setNodeType(AuditProgressNodeTypeEnum.CREDIT_NODE.getCode());
                    auditProgressBO.setOrderNo(orderNo);
                    auditProgressBO.setTaskStatus(creditQueryApplyBO.getQueryStatus());
                    auditProgressBO.setTaskStatusDesc("征信：" + CreditStatusEnum.getNameByCode(auditProgressBO.getTaskStatus()));
                    if (CreditStatusEnum.ENTERED.getCode().equals(creditQueryApplyBO.getQueryStatus())) {
                        auditProgressBO.setStaffId(creditQueryApplyBO.getHandleStaffId());
                        auditProgressBO.setStaffName(creditQueryApplyBO.getHandleStaffName());
                        auditProgressBO.setHandleDate(creditQueryApplyBO.getRecordTime());
                    }
                    auditProgressBOList.add(auditProgressBO);
                } else {
                    return null;
                }
                //通过订单编号查询申请详情，取得申请id
                OrderAuditApplyQuery orderAuditApplyQuery = new OrderAuditApplyQuery();
                orderAuditApplyQuery.createCriteria().andOrderNoEqualTo(orderNo);
                orderAuditApplyQuery.setOrderByClause("apply_id");
                List<OrderAuditApplyDO> orderAuditApplyDOList = orderAuditApplyManager.selectByQuery(orderAuditApplyQuery);
                for (OrderAuditApplyDO orderAuditApplyDO : orderAuditApplyDOList) {
                    //发起申请这个动作也作为一个节点
                    auditProgressBO = new AuditProgressBO();
                    auditProgressBO.setNodeId(orderAuditApplyDO.getApplyId());
                    auditProgressBO.setNodeName("发起：" + ApplyTypeEnum.getApplyTypeEnum(orderAuditApplyDO.getApplyType()).getName());
                    auditProgressBO.setNodeType(AuditProgressNodeTypeEnum.APPLY_NODE.getCode());
                    auditProgressBO.setHandleDate(orderAuditApplyDO.getGmtCreate());
                    auditProgressBO.setOrderNo(orderNo);
                    auditProgressBO.setApplyId(orderAuditApplyDO.getApplyId());
                    auditProgressBO.setStaffId(orderAuditApplyDO.getStaffId());
                    auditProgressBO.setStaffName(orderAuditApplyDO.getStaffName());
                    auditProgressBO.setTaskStatus(orderAuditApplyDO.getApplyStatus());
                    auditProgressBO.setTaskStatusDesc(ApplyStatusEnum.getNameByCode(auditProgressBO.getTaskStatus()));
                    auditProgressBOList.add(auditProgressBO);
                    //通过申请id查询审核历史列表
                    OrderAuditTaskQuery orderAuditTaskQuery = new OrderAuditTaskQuery();
                    orderAuditTaskQuery.createCriteria().andApplyIdEqualTo(orderAuditApplyDO.getApplyId());
                    orderAuditTaskQuery.setOrderByClause("task_id");
                    for (OrderAuditTaskDO orderAuditTaskDO : orderAuditTaskManager.selectByQuery(orderAuditTaskQuery)) {
                        auditProgressBO = new AuditProgressBO();
                        auditProgressBO.setNodeId(orderAuditTaskDO.getTaskId());
                        auditProgressBO.setNodeName(orderAuditTaskDO.getNodeName());
                        auditProgressBO.setNodeType(AuditProgressNodeTypeEnum.TASK_NODE.getCode());
                        auditProgressBO.setHandleDate(orderAuditTaskDO.getGmtModified());
                        auditProgressBO.setOrderNo(orderNo);
                        auditProgressBO.setApplyId(orderAuditTaskDO.getApplyId());
                        auditProgressBO.setStaffId(orderAuditTaskDO.getApproveStaffId());
                        auditProgressBO.setStaffName(orderAuditTaskDO.getApproveStaffName());
                        auditProgressBO.setTaskStatus(orderAuditTaskDO.getTaskStatus());
                        auditProgressBO.setTaskStatusDesc(TaskStatusEnum.getNameByCode(auditProgressBO.getTaskStatus()));
                        if (orderAuditTaskDO.getApprovalResult() != null) {
                            auditProgressBO.setApprovalResult(orderAuditTaskDO.getApprovalResult());
                            auditProgressBO.setApprovalResultDesc(ApprovalResultEnum.getNameByCode(auditProgressBO.getApprovalResult()));
                            auditProgressBO.setApprovalRemark(orderAuditTaskDO.getApprovalRemark());
                        }
                        auditProgressBO.setFlowNodeId(orderAuditTaskDO.getFlowNodeId());
                        /**如果是SP业务员，则不显示客户分析**/
                        if(!RoleTypeEnum.ROLE_SPSALESMAN.getCode().equals(logedUser.getRoleList().get(0).getRoleCode())){
                            auditProgressBO.setCustomerAnalysis(orderAuditTaskDO.getCustomerAnalysis());
                        }
                        for (Role role : logedUser.getRoleList()) {
                            if (RoleTypeEnum.ROLE_SPSALESMAN.getCode().equals(role.getRoleCode())) {
                                auditProgressBO.setCustomerAnalysis(null);
                            }
                        }
                        auditProgressBOList.add(auditProgressBO);
                    }
                }
                return auditProgressBOList;
            } catch (Exception e) {
                log.error("Exception",e);
                throw new SuzukiCommonException(ErrorCodeEnum.QUERY_ORDER_AUDIT_PROCESS_FAIL);
            }
        } else {
            throw new SuzukiCommonException(ErrorCodeEnum.ORDER_NO_ISNULL);
        }
    }

}
